import Vue from 'vue';
import Vuex from 'vuex';
import { ADD_COUNT } from './mutation-types';
import setup from './modules/setup';
import formObj from './modules/formObj';

import createLogger from 'vuex/dist/logger';
import createPersistedState from "vuex-persistedstate"


Vue.use(Vuex);

function getData() {
    return new Promise((resolve)=>{
        setTimeout(()=>{
            resolve(6666);
        },1000)
    })
}
const moudleA = {
    state: () => ({
        num: 1
    }),
    mutations: {
        incrementA(state) {
            //这里的state是模块的局部状态
            console.log('state',state);
            state.num++;
        }
    },
    getters: {
        doubleNum(state) {
            return state.num * 2;
        },
        sumWithRootCount(state,getters,rootState) {
            console.log(state);
            console.log(getters);
            console.log(rootState);
        }
    },
    actions: {
        incrementA({ state,rootState }) {
            console.log('incrementA',state);
            console.log('rootState',rootState);
        },
    }
}

const moudleB = {
    state: () => ({
        num: 1,
    }),
    mutations: {
        incrementB(state) {
            state.num++;
        }
    }
}

const myPlugin = store => {
    // 当 store 初始化后调用
    store.subscribe((mutation, state) => {
        //console.log('111222');
        // 每次 mutation 之后调用
        // mutation 的格式为 { type, payload }
    })
}

const store = new Vuex.Store({
    state: {
        obj: {
            a: 'aa',
            b: 123
        },
        arr: [
            { id: 1,name: 'tianxia' },
            { id: 2,name: 'xiao'}
        ],
        count: 0,
        count1: 1,
        count2: 2,
        count3: 0,
        count4: 0,
        count5: 5,
        count6: 6,
        count7: 7,
        count8: 8,
        actionCount: 111,
        count1217: 1217,
        count0929: 929,
        count0842: 842,
        count0858: 858,
        count0955: 955,
        count1226: 1226,
        todos: [
            {
                id: 1,
                name: '天下',
                status: true,
            },
            {
                id: 2,
                name: 'wangxiao',
                status: false,
            },
            {
                id: 3,
                name: '哈哈',
                status: true,
            }
        ],
    },
    getters: {
        filterTodos: (state,getters) => {
            console.log('getters',getters);
            return state.todos.filter(todo => todo.status)
        },
        getTodoById: (state) => (id) => {
            return state.todos.find( todo => todo.id === id)
        }
    },
    mutations: {
        changeObj(state,obj) {
            state.obj = obj;
        },
        changeArr(state,arr) {
            state.arr = arr;
        },
        increment(state) {
            state.count++;
        },
        decrement(state) {
            state.count--;
        },
        incrementCount(state,n) {
            state.count1 += n;
        },
        incrementCountObj(state,payLoad) {
            state.count2 += payLoad.num;
        },
        objSubmit(state,payLoad) {
            state.count3 += payLoad.num;
        },
        [ADD_COUNT](state) {
            state.count4++;
        },
        addCount(state) {
            state.count5++;
        },
        count6Event(state,num) {
            console.log('num',num);
            state.count6 += num;
        },
        count7Event(state) {
            state.count7++;
        },
        someMutation(state) {
            setTimeout(()=>{
                state.count8++
            },5000)
        },
        actionIncrement(state,amount) {
            console.log('actionIncrement',amount);
            state.actionCount += amount.num;
        },
        
        incrementAction1217(state,amount) {
            state.count1217 += amount.num;
        },
        increment0929(state,amount) {
            state.count0929 += amount.num;
        },
        actionMutation(state,amount) {
            state.count0842 += amount.num;
        },
        someOtherMutation(state,amount) {
            state.count0858 += amount.num;
        },
        gotData(state,amount) {
            state.count0955 += amount.num;
        },
        action1226Mutation(state) {
            state.count1226++;
        }
    },
    actions: {
        //action 通过store.dispatch 方法触发
        //store.dispatch('increment');
        incrementAsync(context,amount) {
            //context 和store具有相同方法和属性的对象
            console.log('context',context);
            //因此你可以提交context.commit 提交一个mutation
            //当以后介绍到Modules时，你就知道为什么是context，而不是store本身了。 
            setTimeout(()=> {
               context.commit('actionIncrement',amount); 
            },2000)
        },
        incrementAction1217(context,amount) {
            setTimeout(()=>{
                context.commit('incrementAction1217',amount);
            })
        },
        incrementAction0929(context,amount) {
            setTimeout(()=>{
                context.commit('increment0929',amount);
            })
        },
        //组合action
        action0842(context,amount) {
            console.log('amount',amount);
            return new Promise((resolve) => {
                setTimeout(()=>{
                    context.commit('actionMutation',amount);
                    //可以把请求接口得到的数据放在resolve中
                    resolve(1);
                },1000);
            })
        },
        action0858({ commit,dispatch },amount) {
            return dispatch('action0842',amount).then(()=>{
                commit('someOtherMutation',amount);
            })
        },
        action1226({commit}) {
            commit('action1226Mutation');
        },
        //利用async／await
        async actionA({ commit },amount) {
            commit('gotData',amount,await getData());
        },
    },
    modules: {
        a: moudleA,
        b: moudleB,
        setup: setup,
        formObj: formObj,
        acount: {
            //带命名空间的模块
            namespaced: true,
            state: ()=> ({

            }),
            getters: {
                isAdmin() {

                },
                someGetter(state,getters,rootState,rootGetters) {
                   console.log('state',state);
                   console.log('getters',getters);
                   console.log('rootState',rootState);
                   console.log('rootGetters',rootGetters);
                }
            },
            actions: {

            },
            mutations: {

            },

            //嵌套模块
            modules: {
                //继承父模块的命名空间
                myPage: {
                    state: () => ({
                        pageCount: 666,
                        myPageList: [
                            {
                                name: 'xiao1',
                                status: true,
                            },
                            {
                                name: 'xiao2',
                                status: false,
                            }
                        ]
                    }),
                    getters: {
                       filterMyPageList(state) {
                           console.log('filterMyPageList------',state);
                           return state.myPageList.filter((item)=> item.status);
                       }
                    },
                    mutations: {
                        pageMutations(state) {
                            state.pageCount++;
                        }
                    },
                }
            }
        }
    },
    plugins: [
        createLogger(),
        myPlugin,
        createPersistedState({
            storage: window.localStorage
        })
    ]
})



//动态注册一个模块
store.registerModule('nested',{
    state: {
        num: 1,
    }
})
//为什么通过store.state访问模块
//console.log('store------',store.state.myModule);

//注册嵌套模块
store.registerModule(['nested','myModule'],{
    state: {
        num: 2
    }
})

//console.log('store123456',store.state.nested.myModule);


//热重载
if(module.hot) {
    module.hot.accept([store.mutations,'./modules/setup'],()=>{
        const newMutations = require(store.mutations).default;
        const newModuleSetup = require('./modules/setup').default;
        //加载新模块
        store.hotUpdate({
            mutations: newMutations,
            modules: {
                setup: newModuleSetup
            }
        })
    })
}

console.log('store',store);
export default store;